﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Configuration;
using System.Collections;

namespace WXYW
{
    public partial class FinishMaintaince : System.Web.UI.Page
    {
        public int RecordsNumber { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindApplicaton();                
            }
        }

        private void BindApplicaton()
        {
            try
            {
                ApplicationService service = new ApplicationService();
                List<ApplicationForm> forms = service.GetApplicationsNeedSend(ContextService.CurrentAccount, keyWordTextBox.Text.Trim());
                applicationGridView.DataSource = forms;
                applicationGridView.DataBind();
                RecordsNumber = forms.Count;
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FinishMaintaince::BindApplicaton");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息绑定发生错误，请刷新页面重试，如持续出现该错误请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        protected void applicationGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0 && e.NewPageIndex < applicationGridView.PageCount)
            {
                applicationGridView.PageIndex = e.NewPageIndex;
                BindApplicaton();
            }
        }

        protected void applicationGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
                ApplicationForm form = e.Row.DataItem as ApplicationForm;
                ((HyperLink)e.Row.FindControl("HyperLink1")).NavigateUrl = string.Format("~/ViewApplicationDetailNeedSend.aspx?{0}={1}", Constants.QUERYSTR_APPLICATION_ID, form.ApplicationID);
            }
            if (e.Row.RowType == DataControlRowType.Pager)
            {
                DropDownList pageDDL = e.Row.FindControl("pageDDL") as DropDownList;
                for (int index = 1; index <= applicationGridView.PageCount; index++)
                {
                    pageDDL.Items.Add(index.ToString());
                }
                pageDDL.SelectedValue = (applicationGridView.PageIndex + 1).ToString();
            }
        }

        protected IEnumerable GridView_MustAddARow(IEnumerable data)
        {
            List<ApplicationForm> dds = new List<ApplicationForm>();
            dds.Add(new ApplicationForm());
            return dds;
        }

        protected void pageDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList pageDDL = sender as DropDownList;
            applicationGridView.PageIndex = Convert.ToInt32(pageDDL.SelectedIndex);
            BindApplicaton();
        }

        protected void sendEmailLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService applicatonservice = new ApplicationService();
                ApplicationProductService productService = new ApplicationProductService();
                ApplicationForm applicationForm = applicatonservice.GetApplicationFormByID(long.Parse(SelectedApplication.Value));
                applicationForm.NortificationDatetime = DateTime.Now; // 其实并无意义
                applicationForm.SendWay = "A"; // 其实并无意义

                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }
                foreach (ApplicationProduct product in applicationForm.ApplicationProduct)
                {
                    if (!product.ApplicationFormReference.IsLoaded)
                    {
                        product.ApplicationFormReference.Load();
                    }
                    if (!product.ApplicationForm.GatheringReference.IsLoaded)
                    {
                        product.ApplicationForm.GatheringReference.Load();
                    }

                    if (product.RepairCompleteDateTime.HasValue && !product.SendBackTime.HasValue &&
                       (!(product.IsQuotePrice.HasValue && product.IsQuotePrice.Value) || !(product.IsDecideToRepair.HasValue && product.IsDecideToRepair.Value) || product.ApplicationForm.Gathering != null) &&
                        (product.UpgradeForm.Count() == 0 || product.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || product.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0))
                    {
                        product.SendWay = "A";
                        product.Status = "已发货待客户收货确认";
                        product.NoticeClientDateTime = DateTime.Now;
                        product.SendBackTime = DateTime.Now;
                    }
                    productService.UpdateProduct(product);
                }

                if (applicationForm.ApplicationProduct.Where(p => !p.SendBackTime.HasValue).Count() == 0)
                {
                    applicationForm.Status = "已发货待客户收货确认";
                    applicationForm.SendBackDateTime = DateTime.Now;
                    applicatonservice.UpdateApplication(applicationForm);
                }                

                EmailService.SendEmail(receiverLbl.Text, "发货通知", BodyTxtBox.Text);
                if (isSendSMSChkBox.Checked)
                {
                    SMSService.SendSMS(SMSTxtBox.Text, mobilePhoneLbl.Text);
                }
                MsgLbl.Text = "自取通知邮件已成功发送。";

                BindApplicaton();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FinishMaintaince.aspx.cs -> sendEmailLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        protected void getBySelfLnk_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService applicationService = new ApplicationService();
                ApplicationForm selectedApplication = applicationService.GetApplicationFormByID(Convert.ToInt64(((LinkButton)sender).CommandArgument));
                if (!selectedApplication.UserReference.IsLoaded)
                {
                    selectedApplication.UserReference.Load();
                }

                string producttypestring = string.Empty;
                if (!selectedApplication.ApplicationProduct.IsLoaded)
                {
                    selectedApplication.ApplicationProduct.Load();
                }
                foreach (ApplicationProduct product in selectedApplication.ApplicationProduct)
                {
                    //if (product.Status.Equals("维修完毕待发货") && !product.SendBackTime.HasValue)
                    if (!product.ApplicationFormReference.IsLoaded)
                    {
                        product.ApplicationFormReference.Load();
                    }
                    if (!product.ApplicationForm.GatheringReference.IsLoaded)
                    {
                        product.ApplicationForm.GatheringReference.Load();
                    }
                    if (product.RepairCompleteDateTime.HasValue && !product.SendBackTime.HasValue &&
                        (!(product.IsQuotePrice.HasValue && product.IsQuotePrice.Value) || !(product.IsDecideToRepair.HasValue && product.IsDecideToRepair.Value) || product.ApplicationForm.Gathering != null) &&
                        (product.UpgradeForm.Count() == 0 || product.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || product.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0))
                    {
                        if (!product.ProductTypeReference.IsLoaded)
                        {
                            product.ProductTypeReference.Load();
                        }
                        if (string.IsNullOrEmpty(producttypestring.Trim()))
                        {

                            producttypestring = product.ProductType.ProductTypeName;
                        }
                        else
                        {
                            producttypestring += "," + product.ProductType.ProductTypeName;
                        }
                    }
                }

                if (!ContextService.CurrentAccount.ServiceStationReference.IsLoaded)
                {
                    ContextService.CurrentAccount.ServiceStationReference.Load();
                }

                SelectedApplication.Value = selectedApplication.ApplicationID.ToString();
                receiverLbl.Text = selectedApplication.User.UserEmail;
                contactLbl.Text = selectedApplication.User.ContactPerson;
                BodyTxtBox.Text = string.Format(ConfigurationManager.AppSettings["SendProductEmailA"].ToString(), selectedApplication.User.ContactPerson, selectedApplication.ApplicationCode, producttypestring, ContextService.CurrentAccount.ServiceStation.Name, ContextService.CurrentAccount.ServiceStation.Phone + " " + ContextService.CurrentAccount.ServiceStation.ContactPerson);
                mobilePhoneLbl.Text = selectedApplication.User.UserMobilePhone;
                SMSTxtBox.Text = string.Format("神州数码网络客服中心提示 尊敬的{0}客户您好，您送修的RMA NO.{1}已修复并已安排发货，您可致电01058859855查询相关信息，神州数码客服中心01082707718", selectedApplication.User.ContactPerson, selectedApplication.ApplicationCode);
                EmailNoticeModalPopupExtender.Show();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FinishMaintaince.aspx.cs -> getBySelfLnk_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        protected void sendByExpressLnk_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("SendProductForm.aspx?{0}={1}", Constants.QUERYSTR_APPLICATION_ID, Convert.ToInt64(((LinkButton)sender).CommandArgument)));
        }

        protected void applicationGridView_DataBound(object sender, EventArgs e)
        {
            if (applicationGridView.BottomPagerRow != null)
            {
                applicationGridView.BottomPagerRow.Visible = true;
            }
        }

        protected void searchLinkButton_Click(object sender, EventArgs e)
        {
            BindApplicaton();
        }

        protected void resetLinkButton_Click(object sender, EventArgs e)
        {
            keyWordTextBox.Text = "";
            BindApplicaton();
        }
    }
}
